var flag = true;
layui.use(['form','table', 'layer'],
function() {
	$ = layui.jquery;
	var form = layui.form,
	layer = layui.layer;
    var table = layui.table;

	 //监听提交
	form.on('submit(add)',
	function(data) {
		if(flag)
		{
			flag = false;
			$("#signupForm").ajaxSubmit(function (message) {
				 console.log(message);
                 
                 if(message.code == 10001)
				 {
					layer.msg("执行成功", {
						icon: 6
					},
					function() {
						window.location.reload();
					});
				 }else{
					layer.msg(message.msg, {
						icon: 5
					},
					function() {
                        flag = true;
						//window.location.reload();
					});
				 }
			});
		}else{
			layer.msg('正在提交。。。', {icon: 6});
		}
		return false;
	});
    var data_sure = [];
    window.GetValue = function(obj)
    {
        var gidarr = [];
        for (i in data_sure) 
        {
            gidarr.push(data_sure[i].goods_id);
        }
        var str = '';
        for (i in obj) 
        {
           if($.inArray(obj[i].goods_id,gidarr) < 0)
            {
               obj[i]['imeitext'] = "----------";
               obj[i]['sntext'] = "----------";
               obj[i]['num'] = "1";
               obj[i]['pricetype'] = '1';
               obj[i]['reason'] = "<button class='layui-btn' type='button' onclick=\"return del_cancel('"+obj[i].goods_id+"')\">取 消</button>";
               data_sure.push(obj[i]); 
            }
        }
        var a , b , c = '';
        var gids = '';
        var prices = '';
        var numbers = '';
        for (i in data_sure) 
        {
            a = $("#imeitext-"+data_sure[i].goods_id).val()==undefined?'':$("#imeitext-"+data_sure[i].goods_id).val();
            b = $("#sntext-"+data_sure[i].goods_id).val()==undefined?'':$("#sntext-"+data_sure[i].goods_id).val();
            c = $("#num-"+data_sure[i].goods_id).val()==undefined?'1':$("#num-"+data_sure[i].goods_id).val();
            
            gids += data_sure[i].goods_id+',';
            prices += data_sure[i].selling_price+',';
            numbers += '1,';
            
            str += "<input type='hidden' id='imeitext-"+data_sure[i].goods_id+"' name='imei[]' value='"+a+"'/>";
            str += "<input type='hidden' id='sntext-"+data_sure[i].goods_id+"' name='sn[]' value='"+b+"'/>";
            str += "<input type='hidden' id='num-"+data_sure[i].goods_id+"' name='number[]' value='"+c+"'/>";
            str += "<input type='hidden' name='gid[]' value='"+data_sure[i].goods_id+"'/>";
        }
        $("#hidden-content").html(str);
        gids = gids.substr(0, gids.length - 1);
        prices = prices.substr(0, prices.length - 1);
        numbers = numbers.substr(0, numbers.length - 1);
        activity(gids,prices,numbers);
        total_order(prices,numbers);
        //展示已知数据
          table.render({
            elem: '#dataTables-sure'
            ,cols: [[ //标题栏
              {field: 'goods_id', title: '序号'}
              ,{field: 'goods_sn', title: '产品编号'}
              ,{field: 'goods_name', title: '产品名称'}
              ,{field: 'imeitext', title: 'IMEI',edit: 'text'}
              ,{field: 'sntext', title: 'S/N',edit: 'text'}
              ,{field: 'selling_price', title: '零售单价（元）'}
              ,{field: 'trade_price', title: '批发价（元）'}
              ,{field: 'num', title: '数量',edit: 'text'}
              ,{field: 'unit', title: '单位'}
              ,{field: 'pricetype', title: '售货价类型',templet: '#selectGxmc',sort:false}
              ,{field: 'reason', title: '操作'}
            ]]
            ,data: data_sure
          });
    }
    //监听单元格编辑
  table.on('edit(dataTables-sure)', function(obj){
    $("#"+obj.field+"-"+obj.data.goods_id).val(obj.value);
    changeactiv();
  });
  //监听select
	form.on('select(zflx)',
	function(data) {
        var id = $(this).closest('tr').data('index');
        data_sure[id].pricetype = data.value;
		changeactiv();
	});
    //监听活动select
	form.on('select(act_bute)',
	function(data) {
        var cked = $('#radio-tab input[name="act"]:checked').val();
        if(cked == 1)
        {
            activ_total_order();
        }
	});
    //监听活动单选radio
	form.on('radio(acttype)',
	function(data) {
        var cked = $('#radio-tab input[name="act"]:checked').val();
        if(cked == 1)
        {
            activ_total_order();
        }
	});
    form.on('radio(acty)',
	function(data) {
        var cked = $('#radio-tab input[name="act"]:checked').val();
        if(cked == 1)
        {
            activ_total_order();
        }else{
            var prices = '';
            var numbers = '';
            for (i in data_sure) 
            {
                if(data_sure[i].pricetype == 1)
                {
                    prices += data_sure[i].selling_price+',';
                }else{
                    prices += data_sure[i].trade_price+',';
                }
                numbers += data_sure[i].num+',';
            }

            prices = prices.substr(0, prices.length - 1);
            numbers = numbers.substr(0, numbers.length - 1);
            total_order(prices,numbers);
        }
	});
     /**
    * 选择活动时金额变化
    */
    function activ_total_order()
    {
        var checked = $('#IsPurchased input[name="act_type"]:checked').val();
        var id = '';
        
        if(checked == 0)
        {
            id = $('#manjian_id').val();
        }else if(checked == 1)
        {
            id = $("#manzhe_dd .layui-this").attr('lay-value'); 
        }else if(checked == 3)
        {
            id = $("#zhekou_dd .layui-this").attr('lay-value'); 
        }else{
            var prices = '';
            var numbers = '';
            for (i in data_sure) 
            {
                if(data_sure[i].pricetype == 1)
                {
                    prices += data_sure[i].selling_price+',';
                }else{
                    prices += data_sure[i].trade_price+',';
                }
                numbers += data_sure[i].num+',';
            }

            prices = prices.substr(0, prices.length - 1);
            numbers = numbers.substr(0, numbers.length - 1);
            total_order(prices,numbers);
        }
        var params = {};
        var gids = '';
        var prices = '';
        var numbers = '';
        for (i in data_sure) 
        {
            gids += data_sure[i].goods_id+',';
            if(data_sure[i].pricetype == 1)
            {
                prices += data_sure[i].selling_price+',';
            }else{
                prices += data_sure[i].trade_price+',';
            }
            numbers += data_sure[i].num+',';
        }

        params.gids = gids.substr(0, gids.length - 1);
        params.prices = prices.substr(0, prices.length - 1);
        params.numbers = numbers.substr(0, numbers.length - 1);
        params.id = id;
        
        $.ajax({
            type: "POST",
            url: "/shop/addorder/countorderpay.html",
            cache: false, //禁用缓存
            data: params, //传入组装的参数
            dataType: "json",
            success: function (result) {
                console.log(result);
                result = result<0?0:result;
                $('#payorder').val(result);
                $('#payawait').val(result);
                $('#actual').val(0);
                $('#payrecall').val(0);
            },
            error:function () {
                parent.layer.msg('网络错误', {icon: 5});
            }
        })
    }
  /*搜索指定商品*/
  window.search = function(obj)
  {
      var params = {};
        params.value = $("#"+obj).val();
        params.field = obj;
      $.ajax({
            type: "POST",
            url: "/shop/addorder/ogoodsinfo.html",
            cache: false, //禁用缓存
            data: params, //传入组装的参数
            dataType: "json",
            success: function (result) {
                if(result.code==10001){
                    var gidarr = [];
                    for (i in data_sure) 
                    {
                        gidarr.push(data_sure[i].goods_id);
                    }
                    if($.inArray(result.option.goods_id,gidarr) < 0)
                    {
                       GetValue([result.option]); 
                    }else{
                        parent.layer.msg('数据已存在', {icon: 5});
                    }
                }else{
                    parent.layer.msg('搜索为空', {icon: 5});
                }
            },
            error:function () {
                parent.layer.msg('网络错误', {icon: 5});
            }
        })
  }
  /*删除*/
  window.del_cancel = function(gid)
  {
      var can_data = [];
      var a , b , c = '';
      var str = '';
        for (i in data_sure) 
        {
            if(data_sure[i]['goods_id'] != gid)
            {
                a = $("#imeitext-"+data_sure[i].goods_id).val()==undefined?'':$("#imeitext-"+data_sure[i].goods_id).val();
                b = $("#sntext-"+data_sure[i].goods_id).val()==undefined?'':$("#sntext-"+data_sure[i].goods_id).val();
                c = $("#num-"+data_sure[i].goods_id).val()==undefined?'1':$("#num-"+data_sure[i].goods_id).val();
                
                str += "<input type='hidden' id='imeitext-"+data_sure[i].goods_id+"' name='imei[]' value='"+a+"'/>";
                str += "<input type='hidden' id='sntext-"+data_sure[i].goods_id+"' name='sn[]' value='"+b+"'/>";
                str += "<input type='hidden' id='num-"+data_sure[i].goods_id+"' name='number[]' value='"+c+"'/>";
                str += "<input type='hidden' name='gid[]' value='"+data_sure[i].goods_id+"'/>";
                
                can_data.push(data_sure[i]);
            }
        }
        data_sure = can_data;
        $("#hidden-content").html(str);
        //展示已知数据
          table.render({
            elem: '#dataTables-sure'
            ,cols: [[ //标题栏
              {field: 'goods_id', title: '序号'}
              ,{field: 'goods_sn', title: '产品编号'}
              ,{field: 'goods_name', title: '产品名称'}
              ,{field: 'imeitext', title: 'IMEI',edit: 'text'}
              ,{field: 'sntext', title: 'S/N',edit: 'text'}
              ,{field: 'selling_price', title: '零售单价（元）'}
              ,{field: 'trade_price', title: '批发价（元）'}
              ,{field: 'num', title: '数量',edit: 'text'}
              ,{field: 'unit', title: '单位'}
              ,{field: 'pricetype', title: '售货价类型',templet: '#selectGxmc',sort:false}
              ,{field: 'reason', title: '操作'}
            ]]
            ,data: data_sure
          });
          changeactiv();
        return false;
  }
  /**
  * 父页面数据传递到子页面
  */
  window.open_data = function()
  {
      return data_sure;
  }
  /**
  * 修改数量或者售货类型
  */
  function changeactiv()
  {
        var gids = '';
        var prices = '';
        var numbers = '';
        for (i in data_sure) 
        {
            gids += data_sure[i].goods_id+',';
            if(data_sure[i].pricetype == 1)
            {
                prices += data_sure[i].selling_price+',';
            }else{
                prices += data_sure[i].trade_price+',';
            }
            numbers += data_sure[i].num+',';
        }

        gids = gids.substr(0, gids.length - 1);
        prices = prices.substr(0, prices.length - 1);
        numbers = numbers.substr(0, numbers.length - 1);
        activity(gids,prices,numbers);
        var cked = $('#radio-tab input[name="act"]:checked').val();
        if(cked == 1)
        {
            activ_total_order();
        }else{
            total_order(prices,numbers);
        }
  }
  /**
  * 添加活动信息
  */
  function activity(gids,prices,numbers)
  {
      var params = {};
      params.gids = gids;
      params.prices = prices;
      params.numbers = numbers;
      
      console.log(params);
      $.ajax({
            type: "POST",
            url: "/shop/addorder/orderactiv.html",
            cache: false, //禁用缓存
            data: params, //传入组装的参数
            dataType: "json",
            success: function (result) {
                console.log(result)
                /*满减*/
                $("#manjian").val(result.manjian.act_name);
                $("#manjian_id").val(result.manjian.activity_id);
                /*满折*/
                var zstr = '<option value="0">请选择活动</option>';
                for (i in result.manzhe) 
                {
                    zstr += '<option value="'+result.manzhe[i].activity_id+'">'+result.manzhe[i].act_name+'</option>';
                }
                $("#manzhe").html(zstr);
                /*满赠*/
                var sstr = '<option value="0">请选择活动</option>';
                for (i in result.manzen) 
                {
                    sstr += '<option value="'+result.manzen[i].activity_id+'">'+result.manzen[i].act_name+'</option>';
                }
                $("#manzen").html(sstr);
                /*折扣*/
                var kstr = '<option value="0">请选择活动</option>';
                for (i in result.zhekou) 
                {
                    kstr += '<option value="'+result.zhekou[i].activity_id+'">'+result.zhekou[i].act_name+'</option>';
                }
                $("#zhekou").html(kstr);
                form.render('select');
            },
            error:function () {
                parent.layer.msg('网络错误', {icon: 5});
            }
        })
    }
    /**
    * 计算订单总金额
    */
    function total_order(prices,numbers)
    {
         var price = prices.split(',');
         var number = numbers.split(',');
         
         var total_price = 0;
         for (i in price) 
         {
            total_price = accAdd(total_price, accMul(price[i], number[i]));
         }
        total_price = total_price<0?0:total_price;
        $('#payorder').val(total_price);
        $('#payawait').val(total_price);
        $('#actual').val(0);
        $('#payrecall').val(0);
    }
    /**
    * 实际支付
    */
    window.payactual = function(obj)
    {
        /*总价*/
        var total_price = parseFloat($('#payorder').val());
        /*实际收款*/
        var actual_price = parseFloat($(obj).val());
        /*总价等于实际收款*/
        if(total_price == actual_price)
        {
            $('#payawait').val(0);
            $('#payrecall').val(0);
        }
        /*总价大于实际收款*/
        if(total_price > actual_price)
        {
            var await_price = accSub(total_price, actual_price);
            $('#payawait').val(await_price);
            $('#payrecall').val(0);
        }
        /*总价小于实际收款*/
        if(total_price < actual_price)
        {
            var recall_price = accSub(actual_price, total_price);
            $('#payawait').val(0);
            $('#payrecall').val(recall_price);
        }
    }
    /**
     ** 乘法函数，用来得到精确的乘法结果
     ** 说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
     ** 调用：accMul(arg1,arg2)
     ** 返回值：arg1乘以 arg2的精确结果
     **/
    function accMul(arg1, arg2) {
        var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
        try {
            m += s1.split(".")[1].length;
        }
        catch (e) {
        }
        try {
            m += s2.split(".")[1].length;
        }
        catch (e) {
        }
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    }
    /**
     ** 加法函数，用来得到精确的加法结果
     ** 说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
     ** 调用：accAdd(arg1,arg2)
     ** 返回值：arg1加上arg2的精确结果
     **/
    function accAdd(arg1, arg2) {
        var r1, r2, m, c;
        try {
            r1 = arg1.toString().split(".")[1].length;
        }
        catch (e) {
            r1 = 0;
        }
        try {
            r2 = arg2.toString().split(".")[1].length;
        }
        catch (e) {
            r2 = 0;
        }
        c = Math.abs(r1 - r2);
        m = Math.pow(10, Math.max(r1, r2));
        if (c > 0) {
            var cm = Math.pow(10, c);
            if (r1 > r2) {
                arg1 = Number(arg1.toString().replace(".", ""));
                arg2 = Number(arg2.toString().replace(".", "")) * cm;
            } else {
                arg1 = Number(arg1.toString().replace(".", "")) * cm;
                arg2 = Number(arg2.toString().replace(".", ""));
            }
        } else {
            arg1 = Number(arg1.toString().replace(".", ""));
            arg2 = Number(arg2.toString().replace(".", ""));
        }
        return (arg1 + arg2) / m;
    }
    /**
     ** 减法函数，用来得到精确的减法结果
     ** 说明：javascript的减法结果会有误差，在两个浮点数相减的时候会比较明显。这个函数返回较为精确的减法结果。
     ** 调用：accSub(arg1,arg2)
     ** 返回值：arg1加上arg2的精确结果
     **/
    function accSub(arg1, arg2) {
        var r1, r2, m, n;
        try {
            r1 = arg1.toString().split(".")[1].length;
        }
        catch (e) {
            r1 = 0;
        }
        try {
            r2 = arg2.toString().split(".")[1].length;
        }
        catch (e) {
            r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
        n = (r1 >= r2) ? r1 : r2;
        return ((arg1 * m - arg2 * m) / m).toFixed(n);
    }
});

function userAjax(obj,ty)
    {
        var params = {};
        params.sreach = $(obj).val();
        params.ty = ty;
        $.ajax({
            type: "POST",
            url: "/shop/addorder/eachuser.html",
            cache: false, //禁用缓存
            data: params, //传入组装的参数
            dataType: "json",
            success: function (result) {
                console.log(result)
                if(result.code==10001){
                    var str = '';
                    var urls = '';
                    for (i in result.option) {
                        urls = '/shop/addorder/userinfo/id/'+result.option[i]['user_id']+'.html';
                        str += '<span class="chakan span_nav" style="cursor:pointer;" onclick=\'xadmin.open("用户信息","'+urls+'",1000,600)\'>'+result.option[i]['user_sn']+'</span>&nbsp;&nbsp;';
                    }
                    $('#userdata').html(str);
                }else{
                    $('#userdata').html('');
                }
            },
            error:function () {
                parent.layer.msg('网络错误', {icon: 5});
            }
        })
    }
